<template>
  <div class="common-layout">
    <span style="font-size:30px">题库生成</span>
    <el-divider />
    <el-row >
      <el-col :span="16" :offset="1">
        <el-card class="upload-card" shadow="never">
          <template #header>
            <div class="card-header">
              上传文件（支持 txt、doc、docx、pdf，最多 5 个文件，≤500KB）
            </div>
          </template>
          <div class="upload-container">
            <el-upload class="upload-demo" drag multiple :auto-upload="false" :on-change="handleFileChange"
              :before-upload="beforeUpload" :file-list="files" :limit="10" :on-exceed="handleExceed" :show-file-list="false">
              <el-icon class="el-icon--upload">
                <UploadFilled />
              </el-icon>
              <div class="el-upload__text">
                拖拽文件到此处或 <em>点击上传</em>
              </div>
            </el-upload>
            <div class="file-list-container">
              <div v-for="file in files" :key="file.uid" class="el-upload-list__item">
                <el-icon>
                  <UploadFilled />
                </el-icon>
                <span class="el-upload-list__item-name">{{ file.name }}</span>
                <el-icon class="delete-icon" @click.stop="removeFile(file)">
                  <Close />
                </el-icon>
              </div>
              <div v-if="files.length === 0" class="empty-tip">
                暂无待上传文件
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮区域 -->
    <el-row class="button-row">
      <el-col :span="6" class="button-wrapper">
        <el-button type="primary" @click="uploadFile">
          上传
          <el-icon class="el-icon--right">
            <Upload />
          </el-icon>
        </el-button>
      </el-col>
      <el-col :span="6" class="button-wrapper">
        <el-button type="danger" @click="clearFiles">
          清空
          <el-icon class="el-icon--right">
            <Close />
          </el-icon>
        </el-button>
      </el-col>
      <el-col :span="6" class="button-wrapper">
        <el-button type="success" @click="generateQuestion">
          生成题库
          <el-icon class="el-icon--right">
            <Upload />
          </el-icon>
        </el-button>
      </el-col>
    </el-row>

    <!-- 文件穿梭框 -->
    <el-row>
      <el-col :span="16"  :offset="1">
        <div style="text-align: center">
          <el-transfer v-model="rightValue" :data="transferData" filterable :titles="['已上传文件', '生成题库文件']"
            :button-texts="['移除', '加入']" :props="{ key: 'key', label: 'label' }"
            style="margin-top: 30px; display: flex; justify-content: center;"
            class="transfer-box">
          </el-transfer>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ElLoading } from 'element-plus'

export default {
  emits: ['file-read', 'question-read'],
  mounted() {
    console.log('FileUpload component mounted')
    this.loadUploadedFiles()
  },
  data() {
    return {
      files: [],               // 所有上传的文件
      result: '',
      transferData: [],        // 穿梭框数据 [{ key: uid, label: 文件名 }]
      rightValue: []           // 右侧被选中的文件 key 列表
    }
  },
  methods: {
    handleFileChange(file, fileList) {
      this.files = fileList.map(f => ({
        ...f,
        raw: f.raw || f
      }))
      // 更新穿梭框数据
      this.transferData = this.files.map(f => ({
        key: f.uid,
        label: f.name
      }))
    },
    beforeUpload(file) {
      const allowedTypes = [
        'text/plain',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/pdf'
      ]
      const isAllowedType = allowedTypes.includes(file.type)
      const isLt500K = file.size / 1024 < 500

      if (!isAllowedType) this.$message.error('仅支持上传 txt、doc、docx、pdf 格式的文件')
      if (!isLt500K) this.$message.error('上传文件大小不能超过 500KB')

      return isAllowedType && isLt500K
    },
    handleExceed(files, fileList) {
      this.$message.warning('最多只能上传 5 个文件')
    },
    removeFile(file) {
      this.files = this.files.filter(f => f.uid !== file.uid)
      this.transferData = this.transferData.filter(f => f.key !== file.uid)
      this.rightValue = this.rightValue.filter(id => id !== file.uid)
    },
    clearFiles() {
      this.files = []
      this.$message.success('已清除所有待上传文件')
    },

    // 获取文件列表
    async loadUploadedFiles() {
      try {
        const res = await fetch('http://127.0.0.1:5000/files')
        if (!res.ok) throw new Error('获取文件列表失败')
        const data = await res.json()
        console.log(data)
        this.transferData = data.map(file => ({
          key: file,
          label: file
        }))
      } catch (error) {
        console.log('加载文件失败', error)
        this.$message.error('获取文件列表失败')
      }
    },

    // 上传文件到后端
    async uploadFile() {
      if (!this.files.length) {
        this.$message.warning('请先选择文件')
        return
      }

      const formData = new FormData()
      this.files.forEach(file => {
        formData.append("files", file.raw)
      })

      try {
        const res = await fetch("http://127.0.0.1:5000/upload", {
          method: "POST",
          body: formData
        })
        if (!res.ok) throw new Error('上传失败')
        const data = await res.json()

        this.result = data.content || '上传成功'
        this.$message.success('上传成功')
        this.$emit('file-read', {
          name: data.filename,
          content: data.content
        })

        // 自动清空上传框，但保留穿梭框显示（根据已有上传列表）
        this.files = []
      } catch (error) {
        console.error('上传出错:', error)
        this.$message.error('上传失败，请稍后重试')
      }
    },
    async generateQuestion() {
      const loadingInstance = ElLoading.service({ fullscreen: true })
      try {
        // 根据 rightValue 获取要提交的文件
        const selectedFiles = this.transferData.filter(f => this.rightValue.includes(f.key))
        const selectedFileNames = selectedFiles.map(f => f.label)

        const res = await fetch("http://127.0.0.1:5000/generate", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({ selected_files: selectedFileNames })
        })

        if (!res.ok) throw new Error('生成失败')
        const data = await res.json()
        this.result = data.questions || '生成题库失败'
        this.$message.success('生成成功')
        this.$emit('question-read', this.result)
        // ✅ 清空穿梭框右侧文件，让文件返回左侧
        this.rightValue = []
      } catch (error) {
        console.error('生成题库出错:', error)
        this.$message.error('生成失败，请稍后重试')
      } finally {
        loadingInstance.close()
      }
    },
    handleChange(newTargetKeys, direction, moveKeys) {
      console.log('穿梭变化:', newTargetKeys)
    }
  }
}
</script>

<script setup>
import { UploadFilled, Upload, Close, Upload as UploadIcon } from '@element-plus/icons-vue'
</script>

<style scoped>
.upload-card {
  margin-top: 20px;
  padding: 10px;
}

.upload-container {
  display: flex;
  gap: 20px;
}

.upload-demo {
  flex: 1;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  background-color: #fafafa;
}

.file-list-container {
  flex: 1;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  padding: 10px;
  height: 180px; /* 固定高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
  display: flex;
  flex-direction: column;
  gap: 5px;
}

/* 美化滚动条 - Webkit浏览器(Chrome, Safari等) */
.file-list-container::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
}

.file-list-container::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条轨道颜色 */
  border-radius: 4px;
}

.file-list-container::-webkit-scrollbar-thumb {
  background: #c1c1c1; /* 滚动条滑块颜色 */
  border-radius: 4px;
}

.file-list-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8; /* 鼠标悬停时滑块颜色 */
}

/* 兼容Firefox */
.file-list-container {
  scrollbar-width: thin; /* "auto" | "thin" | "none" */
  scrollbar-color: #c1c1c1 #f1f1f1; /* 滑块颜色 轨道颜色 */
}

/* 文件项样式 */
.el-upload-list__item {
  display: flex;
  align-items: center;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  flex-shrink: 0;
  transition: all 0.3s; /* 添加过渡效果 */
}

.el-upload-list__item:hover {
  background-color: #ebedf0; /* 鼠标悬停效果 */
}

/* 文件名样式 */
.el-upload-list__item-name {
  margin: 0 10px;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 13px;
}

/* 删除图标样式 */
.delete-icon {
  cursor: pointer;
  color: #f56c6c;
  transition: color 0.2s;
}

.delete-icon:hover {
  color: #f78989;
}

/* 空状态提示 */
.empty-tip {
  color: #909399;
  text-align: center;
  margin: auto;
  font-size: 14px;
}

.button-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
}

.button-row {
  margin-top: 20px;
}

:deep(.el-transfer-panel) {
  width: 520px;
}

.transfer-box {
  width: 100%;
  height: 300px;
}
</style>